<template>
  <div class="relative">
    <input
      type="text"
      placeholder="请输入城市名称"
      v-model="searchCity"
      @input="handleInput"
    />
    <ul>
      <template v-if="searchCity">
        <li @click="jumpToCity">{{ cityName }}</li>
      </template>
      <template v-else>
        <p>对不起网络似乎除了点问题 请稍后再查询</p>
        <p>似乎没有找到你查找的城市</p>
      </template>
    </ul>
    <!-- 显示保存的城市列表 -->
    <div class="justify-between" v-if="!typing">
      <div v-if="savedCities.length > 0" class="saved-cities">
        <!-- <h3>已保存的城市</h3> -->
        <div class="city-list">
          <div v-for="city in savedCities" :key="city.adcode" class="city-item">
            <span>{{ city.name }}</span>
            <div class="city-actions">
              <button
                @click="viewSavedCity(city.adcode, city.name)"
                class="view-btn"
              >
                查看
              </button>
              <button @click="removeSavedCity(city.adcode)" class="remove-btn">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <h2 class="h2_1" v-if="savedCities.length == 0">
    暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
  </h2>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const searchCity = ref('')
const cityName = ref('')
const typing = ref(false)
import { useRouter } from 'vue-router'
const router = useRouter()

import { getCityAdcode } from '@/api/index'

import { storeToRefs } from 'pinia'
import { useWeatherStore } from '@/stores/weather'
const { searchCityInfo } = storeToRefs(useWeatherStore())

const savedCities = ref([])
// 获取保存的城市列表
const getSavedCities = () => {
  const cities = JSON.parse(localStorage.getItem('savedCities') || '[]')
  savedCities.value = cities
}

// 删除保存的城市
const removeSavedCity = (adcode) => {
  const index = savedCities.value.findIndex((city) => city.adcode === adcode)
  if (index !== -1) {
    savedCities.value.splice(index, 1)
    localStorage.setItem('savedCities', JSON.stringify(savedCities.value))
  }
}

// 查看保存的城市
const viewSavedCity = (adcode, name) => {
  router.push({
    path: '/city/:cityName?',
    query: {
      cityAdcode: adcode,
      cityName: name,
    },
  })
}

onMounted(() => {
  getSavedCities()
})

//输入框输入内容时触发
let typingTimeout;

const handleInput = async () => {
  typing.value = true
  cityName.value = ''
  
  // 清除之前的定时器
  if (typingTimeout) {
    clearTimeout(typingTimeout)
  }
  
  // 设置新的定时器，在用户停止输入500ms后将typing设置为false
  typingTimeout = setTimeout(() => {
    typing.value = false
  }, 500)
  
  if (searchCity.value.trim()) {
    const res = await getCityAdcode(searchCity.value)

    //根据返回值回复消息
    if (!res.geocodes || res.geocodes[0].city.length == 0) {
      cityName.value = '似乎没有找到你查找的城市'
    } else {
      cityName.value = res.geocodes[0].city
      searchCityInfo.value = res.geocodes[0]
    }
  }
}

//根据搜索结果去CityView页面,url参数city=cityAdcode
const jumpToCity = () => {
  router.push({
    path: '/city/:cityName?',
    query: {
      cityAdcode: searchCityInfo.value.adcode,
      cityName: cityName.value,
    },
  })
}

//搜索城市数据持久化
const saveCity = () => {
  localStorage.setItem('localCity', JSON.stringify(searchCityInfo.value))
}

//获取本地存储的城市信息
const getLocalCity = () => {
  const localCity = localStorage.getItem('localCity')
  if (localCity) {
    return JSON.parse(localCity)
  } else {
    return {}
  }
}

onMounted(() => {
  const localCity = getLocalCity()
  if (localCity) {
    searchCityInfo.value = localCity
  }
})
</script>

<style lang="scss" scoped>
.relative {
  padding-top: 1rem;
  margin-bottom: 2rem;
  position: relative;
  input {
    outline: none;

    padding-left: 0.25rem;
    padding-right: 0.25rem;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    background-color: transparent;
    border-bottom-width: 1px;
    width: 100%;
    font-family: inherit;
    font-size: 100%;
    font-weight: inherit;
    line-height: inherit;
    color: inherit;
    margin: 0;
    padding: 0;
    overflow-clip-margin: 0px !important;
    overflow: clip !important;

    padding-block: 1px;
    padding-inline: 2px;
  }
  ul {
    --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1),
      0 2px 4px -2px rgb(0 0 0 / 0.1);
    --tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color),
      0 2px 4px -2px var(--tw-shadow-color);
    box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000),
      var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
    --tw-text-opacity: 1;
    color: rgb(255 255 255 / var(--tw-text-opacity));
    padding-left: 0.25rem;
    padding-right: 0.25rem;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    --tw-bg-opacity: 1;
    background-color: rgb(0 78 113 / var(--tw-bg-opacity));
    width: 100%;
    top: 62px;
    position: absolute;
    list-style: none;
    margin: 0;
    padding: 0;
    margin-block-start: 1em;
    margin-block-end: 1em;
    padding-inline-start: 40px;
    unicode-bidi: isolate;
    p {
      display: none;
      margin: 0;
    }
  }

  .justify-between {
    justify-content: space-between;
    display: flex;
    .saved-cities {
      transition-duration: 0.3s;
      padding-left: 1rem;
      padding-right: 1rem;
      padding-top: 0.5rem;
      padding-bottom: 0.5rem;
      --tw-bg-opacity: 1;
      background-color: rgb(0 78 113 / var(--tw-bg-opacity));
      justify-content: space-between;
      cursor: pointer;
      width: 100%;
      display: flex;
      margin-bottom: 1rem;

      h3 {
        margin: 0;
        font-size: inherit;
        font-weight: inherit;
      }
      .city-actions {
        margin-bottom: 1rem;
        button {
          text-align: center;
          --tw-bg-opacity: 1;
          background-color: rgb(234 179 8 / var(--tw-bg-opacity));
          width: 80px;
          cursor: pointer;
          -webkit-appearance: button;
          background-color: transparent;
          background-image: none;
          text-transform: none;
          font-family: inherit;
          font-size: 100%;
          font-weight: inherit;
          line-height: inherit;
          color: inherit;
          margin: 0;
          padding: 0;
        }
      }
    }
  }
}
.h2_1 {
  transition-duration: 0.2s;
  text-align: center;
  margin: 0;
  font-size: inherit;
  font-weight: inherit;
}
</style>
